let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let totalCount = 0;
let allClasses = [];
let filteredClasses = [];
let currentEditingClassId = null;

function validateClassName(name) {
    const errors = [];

    if (!name || name.trim() === '') {
        errors.push('班级名称不能为空');
    } else if (name.trim().length > 100) {
        errors.push('班级名称长度不能超过100个字符');
    }

    return errors;
}

function validateGrade(grade) {
    const errors = [];

    if (!grade || grade.trim() === '') {
        errors.push('年级不能为空');
    } else if (grade.trim().length > 50) {
        errors.push('年级长度不能超过50个字符');
    }

    return errors;
}

function checkClassExists(name, grade, excludeId = null) {
    const trimmedName = name.trim();
    const trimmedGrade = grade.trim();

    return allClasses.some(cls =>
        cls.name === trimmedName &&
        cls.grade === trimmedGrade &&
        cls.id !== excludeId
    );
}

document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

function initializePage() {
    loadClasses();
    bindEvents();
}

function bindEvents() {
    document.getElementById('searchInput').addEventListener('input', debounce(filterClasses, 300));
    document.getElementById('gradeFilter').addEventListener('change', filterClasses);
    document.getElementById('addClassForm').addEventListener('submit', handleAddClass);
    document.getElementById('editClassForm').addEventListener('submit', handleEditClass);
    document.getElementById('confirmDeleteBtn').addEventListener('click', handleDeleteClass);
    document.getElementById('addClassModal').addEventListener('hidden.bs.modal', resetAddForm);
    document.getElementById('editClassModal').addEventListener('hidden.bs.modal', resetEditForm);
}



async function loadClasses() {
    showLoading();

    try {
        const params = new URLSearchParams({
            page: currentPage,
            page_size: pageSize
        });

        const searchTerm = document.getElementById('searchInput').value.trim();
        if (searchTerm) {
            params.append('search', searchTerm);
        }

        const gradeFilter = document.getElementById('gradeFilter').value;
        if (gradeFilter) {
            params.append('grade', gradeFilter);
        }

        const response = await fetch(`/api/classes?${params}`);
        const result = await response.json();

        if (result.success) {
            const data = result.data;
            allClasses = data.items;
            filteredClasses = [...allClasses];

            totalPages = data.pagination.total_pages;
            currentPage = data.pagination.current_page;
            totalCount = data.pagination.total_count;

            displayClasses();
        } else {
            console.error('加载班级数据失败:', result.msg, result.error);
            showError('加载失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
            showEmptyState();
        }
    } catch (error) {
        console.error('加载班级数据出错:', error);
        showError('加载失败：网络错误');
        displayClasses();
    }
}

function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('classTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'none';
}

function showEmptyState() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('classTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'block';
    updateClassCount(0);
}

function displayClasses() {
    document.getElementById('loadingSpinner').style.display = 'none';

    if (filteredClasses.length === 0) {
        showEmptyState();
        return;
    }

    document.getElementById('classTableContainer').style.display = 'block';
    document.getElementById('emptyState').style.display = 'none';

    renderClassTable(filteredClasses);
    renderPagination();
    updateClassCount(totalCount);
}

function renderClassTable(classes) {
    const tbody = document.getElementById('classTableBody');
    tbody.innerHTML = '';
    
    classes.forEach(classItem => {
        const row = document.createElement('tr');
        row.className = 'fade-in';
        row.innerHTML = `
            <td>${classItem.id}</td>
            <td><strong>${classItem.grade}级${classItem.name}</strong></td>
            <td><span class="badge bg-info">${classItem.grade}级</span></td>
            <td>${formatDateTime(classItem.created_time)}</td>
            <td>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-primary btn-sm"
                            onclick="editClass(${classItem.id})" title="编辑">
                        <i class="fas fa-edit"></i>
                        编辑
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm"
                            onclick="deleteClass(${classItem.id}, '${classItem.grade}级${classItem.name}')" title="删除">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function renderPagination() {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">
            <i class="fas fa-chevron-left"></i>
            上一页
        </a>
    `;
    pagination.appendChild(prevLi);
    
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
            pagination.appendChild(li);
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(li);
        }
    }
    
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">
            <i class="fas fa-chevron-right"></i>
            下一页
        </a>
    `;
    pagination.appendChild(nextLi);
}

function updateClassCount(count) {
    document.getElementById('listCount').textContent = count;
}

function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) return;
    currentPage = page;
    loadClasses();
}

function filterClasses() {
    currentPage = 1;
    loadClasses();
}

function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('gradeFilter').value = '';
    currentPage = 1;
    loadClasses();
}

async function handleAddClass(event) {
    event.preventDefault();

    const form = event.target;
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        return;
    }

    const formData = new FormData(form);
    const classData = {
        name: formData.get('name').trim(),
        grade: formData.get('grade').trim()
    };

    const nameErrors = validateClassName(classData.name);
    const gradeErrors = validateGrade(classData.grade);

    if (nameErrors.length > 0 || gradeErrors.length > 0) {
        const allErrors = [...nameErrors, ...gradeErrors];
        showError('数据验证失败：' + allErrors.join('；'));
        return;
    }

    try {
        const response = await fetch('/api/classes', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(classData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('addClassModal')).hide();
            resetAddForm();
            loadClasses();
        } else {
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('添加班级出错:', error);
        showError('添加失败：网络错误');
    }
}

function editClass(classId) {
    const classItem = allClasses.find(c => c.id === classId);
    if (!classItem) {
        showError('班级不存在');
        return;
    }

    currentEditingClassId = classId;

    document.getElementById('editClassId').value = classItem.id;
    document.getElementById('editClassName').value = classItem.name;
    document.getElementById('editClassGrade').value = classItem.grade;

    new bootstrap.Modal(document.getElementById('editClassModal')).show();
}

async function handleEditClass(event) {
    event.preventDefault();

    const form = event.target;
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        return;
    }

    const formData = new FormData(form);
    const classData = {
        id: parseInt(formData.get('id')),
        name: formData.get('name').trim(),
        grade: formData.get('grade').trim()
    };

    const nameErrors = validateClassName(classData.name);
    const gradeErrors = validateGrade(classData.grade);

    if (nameErrors.length > 0 || gradeErrors.length > 0) {
        const allErrors = [...nameErrors, ...gradeErrors];
        showError('数据验证失败：' + allErrors.join('；'));
        return;
    }

    try {
        const response = await fetch(`/api/classes/${classData.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(classData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('editClassModal')).hide();
            resetEditForm();
            loadClasses();
        } else {
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('更新班级出错:', error);
        showError('更新失败：网络错误');
    }
}

function deleteClass(classId, className) {
    currentEditingClassId = classId;
    document.getElementById('deleteClassInfo').textContent = className;
    new bootstrap.Modal(document.getElementById('deleteClassModal')).show();
}

async function handleDeleteClass() {
    if (!currentEditingClassId) return;

    try {
        const response = await fetch(`/api/classes/${currentEditingClassId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('deleteClassModal')).hide();
            currentEditingClassId = null;
            loadClasses();
        } else {
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('删除班级出错:', error);
        showError('删除失败：网络错误');
    }
}

function resetAddForm() {
    const form = document.getElementById('addClassForm');
    form.reset();
    form.classList.remove('was-validated');
}

function resetEditForm() {
    const form = document.getElementById('editClassForm');
    form.reset();
    form.classList.remove('was-validated');
    currentEditingClassId = null;
}
